package com.elective.courseselect.quartzJob;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.elective.courseselect.config.QuartzConfig;
import com.elective.courseselect.entity.AnswerEntity;
import com.elective.courseselect.entity.ScheduleEntity;
import com.elective.courseselect.service.AnswerService;
import com.elective.courseselect.service.ScheduleService;
import com.elective.status.StatusCode;
import lombok.SneakyThrows;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 定时检查比较时间
 * @author lee
 * @date 2021年10月24日 0:10
 */
public class QuartzJob extends QuartzJobBean {

    protected static final Logger logger = LoggerFactory.getLogger(QuartzJob.class);

    @Autowired
    ScheduleService scheduleService;

    @Autowired
    AnswerService answerService;

    @Autowired
    private Scheduler scheduler;

    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    protected synchronized void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        ScheduleEntity scheduleEntity = scheduleService.searchSchedule();
        //获取当前时间
        Date date = new Date();
        //当前时间大于预选课结束时间,就是预选课时间结束了,不给再预选了 , 并且在抢课时间前的一个时间段，进行结算
        if (date.after(scheduleEntity.getPrepareTimeEnd()) && date.before(scheduleEntity.getSelectTimeStart())) {
            QueryWrapper<AnswerEntity> answerEntityQueryWrapper = new QueryWrapper<>();
            answerEntityQueryWrapper.eq("status", StatusCode.ANSWER_PRE_SELECT);
            if (answerService.list(answerEntityQueryWrapper).isEmpty()) {
                //deleteJob();
            }else{
                answerService.finishPrimary();
            }
        }
    }


    @SneakyThrows
    public void deleteJob() {
        scheduler.pauseTrigger(TriggerKey.triggerKey("syncCheckTimeJobTrigger", QuartzConfig.TRIGGER_GROUP_NAME));
        scheduler.unscheduleJob(TriggerKey.triggerKey("syncCheckTimeJobTrigger",QuartzConfig.TRIGGER_GROUP_NAME));//移除触发器
        scheduler.deleteJob(JobKey.jobKey("syncCheckTimeTask",QuartzConfig.JOB_GROUP_NAME));//删除Job
        logger.info("删除定时任务");
    }

}
